package com.andaily.infrastructure;

import com.andaily.domain.log.FrequencyMonitorLog;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Wrapper HttpClient operations
 *
 * @author Shengzhao Li
 */
public class HttpClientHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientHandler.class);
    //Convert mill seconds to second unit
    private static final int MS_TO_S_UNIT = 1000;
    //Normal http response code
    private static final int NORMAL_RESPONSE_CODE = 200;

    private String url;

    private int maxConnectionSeconds = 0;

    public HttpClientHandler(String url) {
        this.url = url;
    }

    public HttpClientHandler maxConnectionSeconds(int maxConnectionSeconds) {
        this.maxConnectionSeconds = maxConnectionSeconds;
        return this;
    }

    public FrequencyMonitorLog handleAndGenerateFrequencyMonitorLog() {
        FrequencyMonitorLog monitorLog = new FrequencyMonitorLog();

        final long start = System.currentTimeMillis();
        try {
            final HttpResponse response = sendRequest(url);

            monitorLog.normal(isNormal(response))
                    .responseSize(responseSize(response))
                    .costTime(costTime(start));

        } catch (Exception e) {
            monitorLog.costTime(costTime(start))
                    .remark(e.getClass().getSimpleName() + ": " + e.getMessage());
            LOGGER.debug("Send request to url[" + url + "] failed", e);
        }

        return monitorLog;
    }

    private long responseSize(HttpResponse response) {
        return response.getEntity().getContentLength();
    }

    private long costTime(long start) {
        return System.currentTimeMillis() - start;
    }

    private boolean isNormal(HttpResponse response) {
        return response.getStatusLine().getStatusCode() == NORMAL_RESPONSE_CODE;
    }

    private HttpResponse sendRequest(String url) throws Exception {
        HttpGet request = new HttpGet(url);
        addRequestParams(request);
        HttpClient client = new DefaultHttpClient();
        return client.execute(request);
    }

    private void addRequestParams(HttpGet request) {
        if (this.maxConnectionSeconds <= 0) {
            return;
        }
        final BasicHttpParams params = new BasicHttpParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, this.maxConnectionSeconds * MS_TO_S_UNIT);
        request.setParams(params);
    }

}